package com.quyunshuo.module.home.activity.main

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.quyunshuo.edwingoal.base.BaseApplication
import com.quyunshuo.edwingoal.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.room.database.SumDataBase
import com.quyunshuo.module.home.room.entity.Steps
import com.quyunshuo.module.home.util.stepToCalorie
import com.quyunshuo.module.home.util.stepToM
import com.quyunshuo.module.home.util.stepToMillisecond
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Date
import javax.inject.Inject
import kotlin.math.log

/**
 * 首页的VM层
 *
 * @property mRepository HomeRepository 仓库层 通过Hilt注入
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:41 PM
 */
@HiltViewModel
class SharedViewModel @Inject constructor(private val mRepository: HomeRepository) :
    BaseViewModel() {
    private val stepsDao by lazy {
        SumDataBase.getInstance().stepsDao()
    }
    private val stepCounterManager = StepCounterManager
    private val _stepCount = MutableStateFlow(0)
    val stepCount = _stepCount.asStateFlow()
    private var initStep: Long? = null


    fun init() {
        // 初始化计步管理器
        StepCounterManager.initialize(BaseApplication.context)
        if (!StepCounterManager.isSensorAvailable()) {
            return
        }

        StepCounterManager.startListening()

        // 使用协程收集Flow数据
        viewModelScope.launch {
            stepCounterManager.stepCount.collect { it ->
                //1. 这里给到的是总的数据：我需要判断，进行一个记录，因为我只需要拿到今天的数据
                //2. 先查询数据库是否记录了当前的数据。
                if (it == null) return@collect
                if (initStep == null) {
                    initStep = it
                } else {
                    val dStep = it - initStep!!
                    addStep(dStep.toInt())
                    Log.d("longd", "init: $dStep $initStep")
                }

            }
        }
    }


    suspend fun addStep(dStep: Int) {
        withContext(Dispatchers.IO) {
            //查询今天的数据
            val oldData = stepsDao.queryTodayStep(Date())
            var stepCount = dStep
            stepCount += oldData?.stepCount ?: 0

            //然后我们需要进行数据的更新。
            val newStep = Steps(
                stepCount = stepCount,
                date = Date(),
                duration = stepCount.stepToMillisecond(),
                calories = stepCount.stepToCalorie(),
                mileage = stepCount.stepToM(),
            )
            //如果有今天的数据的话，就是更新，如果不是就是插入
            if (oldData != null) {
                //更新
                newStep.id = oldData.id
                stepsDao.insert(newStep)
            } else {
                // 插入
                stepsDao.insert(newStep)

            }
            _stepCount.emit(stepCount)
        }
    }

}
